<template>
  <a-modal
    v-model:visible="show"
    width="700"
    title-align="start"
    ok-text="确认添加"
    class="add-stage-dialog"
    :on-before-ok="save"
  >
    <template #title>
      <CustomTitle title="选择工程阶段" />
    </template>
    <div class="model-content">
      {{ portraitName }}
      <!-- <a-srcollbar style="max-height: 60vh;overflow-y: scroll;"> -->
      <div class="stage-list-item" v-for="(item, index) in stageList" :key="item.portraitId">
        <div class="form-box">
          <a-form layout="inline" :model="item" :rules="rules" ref="formRef">
            <a-form-item hide-label field="stageName">
              <a-input placeholder="请输入阶段名称" v-model.trim="item.stageName" />
            </a-form-item>
            <a-form-item label="排序" field="showSeq" hide-asterisk>
              <a-input v-model="item.showSeq" placeholder="请输入排序" />
            </a-form-item>
            <a-form-item label="启/禁用 " field="status">
              <a-switch v-model="item.status" :unchecked-value="0" :checked-value="1" @change="editStatus(item)" />
            </a-form-item>
          </a-form>
          <img src="../../../../../assets/images/del.png" alt="" @click="deleteStage(item, index)" />
        </div>
        <a-checkbox v-model="item.isSelect" @change="changeSelect(index)"></a-checkbox>
      </div>
      <!-- </a-srcollbar> -->
      <div class="add-icon" :style="{ width: `calc(100% - ${stageList.length != 0 ? 30 : 0}px` }">
        <span @click="addStage"><icon-plus-circle-fill /> 添加阶段</span>
      </div>
    </div>
  </a-modal>
</template>
<script setup lang="ts">
import { computed } from "vue";
import {
  getEngineeringPhaseList,
  cancelCheck,
  deleteCheck,
  deleteStageItem,
  saveStageList,
  updateStageStatus
} from "@/apis/engineeringSettings/process";
import { getCurrentInstance } from "vue";
import type { EngineeringPhase } from "@/apis/engineeringSettings/process/type";
import { Message } from "@arco-design/web-vue";

const props = defineProps({
  portraitId: {
    type: String,
    default: ""
  },
  portraitName: {
    type: String,
    default: ""
  },
  modelValue: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:modelValue", "getPortrait"]);
const show = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
    proxy.$emit("update:modelValue", val);
  }
});

const { proxy }: any = getCurrentInstance();

const changeSelect = async (index: number) => {
  const { isSelect, stageSettingId, portraitId } = stageList.value[index];
  if (!stageSettingId || !portraitId) return;
  if (!isSelect) {
    try {
      const res = await cancelCheck(portraitId as string, stageSettingId as string);
      if (!res.data.isDelete) {
        stageList.value[index].isSelect = true;
        Message.error(res.data.stageMsg);
      }
    } catch (error) {
      stageList.value[index].isSelect = true;
    }
  }
};
const formRef = ref();
const verify = async () => {
  let arr: Promise<boolean>[] = [];
  formRef.value?.forEach((item: any) => {
    arr.push(
      new Promise(resolve => {
        item.validate((error: any) => {
          resolve(error == undefined);
        });
      })
    );
  });
  const result = await Promise.all(arr);
  return result.every(v => v);
};
const stageList = ref<EngineeringPhase[]>([]);
const getEngineeringPhaseListData = async () => {
  try {
    const { data } = await getEngineeringPhaseList(props.portraitId);
    stageList.value = data || [];
  } catch (error) {}
};
const rules = {
  stageName: [
    { required: true, message: "请输入阶段名称", trigger: "blur" },
    { minLength: 1, maxLength: 30, message: "长度在 1 到 30 个字符", trigger: "blur" }
  ],
  showSeq: [
    { required: true, message: "请输入序号", trigger: "blur" },
    { match: /^(?!0$)\d{1,12}$/, message: "请输入1到12位的正整数且大于0" }
  ]
};
const addStage = () => {
  stageList.value.push({
    stageName: "",
    stageType: "",
    showSeq: 1,
    status: 1,
    isSelect: true
  });
};
const deleteStage = async (item: EngineeringPhase, index: number) => {
  if (!item.stageSettingId) {
    stageList.value.splice(index, 1);
  } else {
    try {
      const res = await deleteCheck(item.stageSettingId);
      if (!res.data.isDelete) {
        Message.error(res.data.stageMsg);
      } else {
        await deleteStageItem(item.stageSettingId);
        getEngineeringPhaseListData();
        Message.success("删除成功");
      }
    } catch (error) {}
  }
};
const save = async () => {
  if (!(await verify())) return false;
  try {
    await saveStageList(props.portraitId, stageList.value);
    show.value = false;
    Message.success("保存成功");
    emit("getPortrait");
  } catch (error) {}
  return false;
};

const editStatus = async (item: EngineeringPhase) => {
  try {
    await updateStageStatus(item);
    Message.success("操作成功");
    getEngineeringPhaseListData();
  } catch (error) {
    item.status = 1;
  }
};
onMounted(() => {
  getEngineeringPhaseListData();
});
</script>

<style scoped lang="scss">
@import "../index";

.model-content {
  height: 60vh;

  ::v-deep(.arco-checkbox) {
    margin: 0;
  }

  ::v-deep(.arco-checkbox-icon) {
    border-radius: 50%;
  }

  .stage-list-item {
    margin-top: 10px;
    display: flex;
    gap: 10px;

    .form-box {
      min-height: 50px;
      background: #f5f7fa;
      border: 1px solid #e1e6ed;
      flex: 1;
      display: flex;
      gap: 20px;
      align-items: center;
      padding: 0 20px;

      img {
        width: 20px;
        height: 20px;
      }
    }

    ::v-deep(.arco-form) {
      gap: 20px;
      flex-wrap: nowrap;

      .arco-form-item-label {
        white-space: unset;
      }

      .arco-form-item-wrapper-col:nth-child(1) {
        width: 160px;
      }

      .arco-form-item-wrapper-col:nth-child(3) {
        width: 60px;
      }

      .arco-form-item {
        margin: 0;
      }
    }
  }

  .add-icon {
    height: 50px;
    border: 1px solid #dcdfe6;
    color: #007dff;
    margin-top: 10px;
    display: flex;
    gap: 8px;
    padding: 0 20px;
    align-items: center;
    box-sizing: border-box;
    cursor: pointer;
  }
}

::v-deep(.arco-input-wrapper) {
  background: white;
}
</style>
<style>
.add-stage-dialog {
  .arco-modal {
    width: 600px;
  }

  .arco-modal-header {
    border-bottom: 1px solid #dcdfe6;
  }
}
</style>
